<template>
  <div class="startgroupchat-pages">
    <cp-nav-bar title="选择联系人" class="startgroupchat-nav-bar" left-arrow>
      <template #right>
        <van-button hairline color="#16c2a3" @click="addFriend">完成</van-button>
      </template>
    </cp-nav-bar>
    <van-cell :border="false">
      <div class="contact-item">
        <van-icon name="search" size="20" style="margin-right: 10px" />
        <div class="add-friend-list">
          <template v-for="item in checkList.slice(0, 3)" :key="item.friend_id">
            <van-image
              width="30px"
              height="30px"
              fit="cover"
              radius="4px"
              :src="item.avatar"
              style="margin-right: 5px"
            ></van-image>
          </template>
          <van-icon name="ellipsis" v-if="checkList.length > 3" />
        </div>
        <span class="contact-item-search">
          <input
            type="text"
            placeholder="搜索"
            class="add-friend-search"
            v-model="searchContent"
            @input="searchInput"
          />
        </span>
      </div>
    </van-cell>
    <template v-if="searchContent.length === 0">
      <van-index-bar :sticky="false" :index-list="indexList">
        <van-checkbox-group v-model="checked">
          <template v-for="item in indexList" :key="item">
            <van-index-anchor :index="item" />
            <van-cell
              v-for="data in groupList[item]"
              :key="data.user_id"
              @click="toggle(data, item)"
              clickable
              ><div class="contact-item">
                <van-checkbox
                  style="margin-right: 15px"
                  checked-color="#16c2a3"
                  :name="data.friend_name"
                  :ref="(el) => (checkboxRefs[data?.friend_id] = el)"
                ></van-checkbox>
                <van-image
                  width="38px"
                  height="38px"
                  fit="cover"
                  radius="4px"
                  :src="data.avatar"
                ></van-image>
                <span class="contact-item-text">{{ data.friend_name }}</span>
              </div>
            </van-cell>
          </template>
        </van-checkbox-group>
      </van-index-bar>
    </template>
    <template v-else>
      <template v-if="searchList.length > 0">
        <van-checkbox-group v-model="checked">
          <van-cell
            v-for="data in searchList"
            :key="data.user_id"
            @click="toggleSearch(data)"
            clickable
            ><div class="contact-item">
              <van-checkbox
                style="margin-right: 15px"
                checked-color="#16c2a3"
                :name="data.friend_name"
                :ref="(el) => (checkboxRefs[data?.friend_id] = el)"
              ></van-checkbox>
              <van-image
                width="38px"
                height="38px"
                fit="cover"
                radius="4px"
                :src="data.avatar"
              ></van-image>
              <span class="contact-item-text">{{ data.friend_name }}</span>
            </div>
          </van-cell>
        </van-checkbox-group>
      </template>
      <template v-else>
        <div class="search-empty">- 搜索结果为空 -</div>
      </template>
    </template>
  </div>
</template>
<script setup lang="ts">
import { ref, type ComponentPublicInstance } from 'vue'

const indexList = ref<string[]>([])
const groupList = ref<{ [key: string]: friend[] }>({})
import { createGroupFriend, getGroupFriendList, getSearchFriendList } from '@/services/friend'
import type { friend } from '@/types/friend'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
const getfrendList = async () => {
  const res = await getGroupFriendList()
  indexList.value = res.data.groupList
  groupList.value = res.data?.groupedData
}
getfrendList()

const checked = ref<string[]>([])
const checkboxRefs = ref<{ [key: string]: Element | ComponentPublicInstance | null }>({})
const searchContent = ref('')
const searchList = ref<friend[]>([])
const checkList = ref<friend[]>([])
const router = useRouter()
const searchInput = async (e: Event) => {
  const inputElement = e.target as HTMLInputElement
  if (inputElement.value) {
    const res = await getSearchFriendList(inputElement.value)
    searchList.value = res.data
  }
}
const toggle = (item: friend, index: string) => {
  //这部分的item是用于可以让van-ceil可以联动勾选checkbox用的
  const checkbox = checkboxRefs.value[item.friend_id]
  if (checkbox) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    ;(checkbox as any).toggle()
  }
  //数据的勾选状态的存储用checked.value存储
  const newData = groupList.value[index].filter((data) => {
    return checked.value.includes(data.friend_name)
  })
  checkList.value = newData
}
const toggleSearch = (item: friend) => {
  const checkbox = checkboxRefs.value[item.friend_id]
  if (checkbox) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    ;(checkbox as any).toggle()
  }
  checkList.value = [...checkList.value, item]
}
const addFriend = async () => {
  const numberList = checkList.value.map((item) => item.friend_id)
  const group_name =
    checkList.value.reduce((rcc, item, index) => {
      // 如果是最后一项，不加逗号
      return rcc + item.friend_name + (index === checkList.value.length - 1 ? '' : ',')
    }, '') + '的群聊'
  await createGroupFriend(group_name, numberList)
  showToast('创建群聊成功')
  router.push('/home')
}
</script>
<style lang="scss" scoped>
.startgroupchat-pages {
  padding-top: 46px;
  background-color: var(--bg-primary);
  height: 100vh;
  .startgroupchat-nav-bar {
    background: var(--my-bg-primary);
  }
  .contact-item {
    height: 100%;
    display: flex;
    justify-content: start;
    align-items: center;
    font-size: 16px;
    color: var(--cp-contact-color);

    .contact-item-icon {
      width: 40px;
      height: 40px;
    }
    .contact-item-text {
      margin-left: 12px;
      white-space: nowrap; /* 禁止换行 */
      overflow: hidden; /* 隐藏超出部分 */
      text-overflow: ellipsis; /* 显示省略号 */
      flex: 1;
      text-align: left;
    }
    .contact-item-search {
      font-size: 16px;
      color: rgba(153, 153, 153, 1);
      margin-left: 14px;
      input {
        background-color: var(--chat-input-inset);
      }
    }
  }
  .add-friend-list {
    max-width: 140px;
    overflow-x: scroll;
  }
  .add-friend-search {
    border: none;
    width: 130px;
  }
  .search-empty {
    text-align: center;
    margin-top: 20px;
    color: rgba(153, 153, 153, 1);
  }
}
:deep(.van-button) {
  background-color: var(--my-bg-primary) !important;
  border-color: var(--my-bg-primary) !important;
}
</style>
